<template>
    <el-dialog :title="tagsType == 3? '预览' : '分拆标记'" v-model="dialogVisible" width="1200px" @close="dialogClose" class="file-tags-dialog" top="10vh">
        <div class="tags-container flex">
            <div class="left-container flex" >
                <el-carousel :autoplay="false"  trigger="click" v-loading="documentLoad" ref="carouselRef" :loop="false">
                    <el-carousel-item v-for="(item,index) in documentInfo" :key="index">
                        <!-- <viewer :images="[item.imgPath]"> -->
                            <el-image  :src="item.imgPath" lazy @click="ImgPreview(item.imgPath)" />
                        <!-- </viewer> -->
                    </el-carousel-item>
                    <button class="el-carousel__arrow el-carousel__arrow--left prev-arrow customized-arrow flexCC" :class="{'arrow-disabled': activeIndex == 0}" :disabled="activeIndex == 0" @click="prevStep" v-loading="confirmLoading">
                        <!-- 可以用 Font Awesome 图标或自定义图片 -->
                        <el-icon class="el-icon"><ArrowLeft /></el-icon>
                        <!-- 或使用图片：<img src="/left-arrow.png" alt="上一张"> -->
                    </button>
                    <button class="el-carousel__arrow el-carousel__arrow--right next-arrow customized-arrow flexCC" :class="{'arrow-disabled': activeIndex == documentInfo.length - 1}"  :disabled="activeIndex == documentInfo.length - 1" @click="nextStep" v-loading="confirmLoading">
                        <!-- 可以用 Font Awesome 图标或自定义图片 -->
                        <el-icon class="el-icon"><ArrowRight /></el-icon>
                        <!-- 或使用图片：<img src="/left-arrow.png" alt="上一张"> -->
                    </button>
                </el-carousel>
                <div class="step-btn flexC">
                    <el-button @click="prevOne" :disabled="arrowIndex == 0" plain  :icon="ArrowLeft" :loading="confirmLoading" >上一份</el-button>
                    <p class="step-text ellipsis" :title="activeObj.name">{{ activeObj.name }}</p>
                     <el-button @click="nextCopy" :disabled="arrowIndex == taskTable.length - 1" :loading="confirmLoading" plain  >
                        下一份<el-icon style="margin-left: 5px;"><ArrowRight /></el-icon>
                    </el-button>
                </div>
            </div>
            <div class="right-container">
                <el-form label-width="auto">
                    <el-form-item label="文件名称">
                        {{ activeObj?.name || '--' }}
                    </el-form-item>
                    <el-form-item label="类型">
                        {{ Alltags[activeObj?.tagTypeId] || '--' }}
                    </el-form-item>
                    <div class="tags-Type">
                        <el-radio-group v-model="activeObj.tagTypeId">
                            <el-form-item v-for="(item,key) in fileTypeList" :key="key" style="width: 100%;">
                                <div style="display: block;width: 100%;" :class="key">
                                    <p style="display: block;font-weight: 600;margin-bottom: 5px;">{{ key }}</p>
                                    <el-radio :value="citem.id" size="small" border v-for="(citem,index) in fileTypeList[key]" :key="index">{{citem.name}}</el-radio>
                                </div>
                            </el-form-item>
                        </el-radio-group>
                    </div>
                </el-form>
                <div class="tags-Type-confirm" align="center">
                    <el-button @click="confirmTagType(1)" type="primary" :loading="confirmLoading" size="large">确认</el-button>
                    <el-button @click="handleDelete" type="danger" v-if="tagsType == 2 && activeObj.state != 'Processed'" :loading="DeleteLoading" size="large">删除</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue';
import { useRoute } from 'vue-router';
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import { ProjectTaskQuery, ProjectTaskImages, ProjectTaskFileType, ProjectTaskFileTag, ProjectFileQuery, ProjectTaskFileDelete, delPwConfirm  } from "@/api/project";
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { MD5 } from 'crypto-js'

const { proxy } = getCurrentInstance();
const dialogVisible = ref(false);
const confirmLoading = ref(false);
const DeleteLoading = ref(false);

const carouselRef = ref(null);
const route = useRoute();
const emit = defineEmits(['close']);
const arrowIndex = ref(0);
const tagsType = ref();

const activeIndex = ref(0);
const activeObj = ref({});
const documentInfo = ref([]);
const taskTable = ref([]);
const documentLoad = ref(false);
const fileTypeList = ref([]);
const Alltags = ref({});
const fileTypeLoad = ref(false);

onMounted(() => {
    getFileTags();
    getTaskQuery();
});
// 获取 任务 列表
const getTaskQuery = async () => {
    let fun  = tagsType.value == 2 ? ProjectTaskQuery : ProjectFileQuery;
    const res = await fun({
        projectId: route.query.id,
    });
    if(res.errorCode == 0){
        taskTable.value = res.data.map(item =>{
            return {
                ...item,
               name: item.name || item.title,
            }
        });
    }
}
// 图片 预览 
const ImgPreview = (src) => {
    proxy.$ViewerApi([src]);
}
const open = async (row) => {
    dialogVisible.value = true;    
    activeObj.value = {...row, name: row.name || row.title};
    tagsType.value = row.type;
    TaskImages();
    await getTaskQuery();
    arrowIndex.value = taskTable.value.findIndex(item => item.id == row.id);
};
// 获取 任务 图片   type  open 时 绑定
const TaskImages = async (type) =>{
    documentLoad.value = true;
    let result = await ProjectTaskImages({
        id: route.query.id,
        [tagsType.value == 2 ? 'fileId' : 'documentId']: activeObj.value.id,
    })
    documentLoad.value = false;
    if(result.errorCode == 0){
        documentInfo.value = result.data.map(item => {
            return {
                ...item,
                tagTypeId: item.documentType,
            }
        });        
        
        if(result.data.length != 0){
            activeObj.value.tagTypeId = result.data[0].documentType;
        }

    }
}
// 上一份
const prevOne = async () => {
    arrowIndex.value = arrowIndex.value - 1
    let row = taskTable.value[arrowIndex.value];
    // tagsType.value = row.type;
    activeObj.value = {...row};
    TaskImages();
}
// 下一份
const nextCopy = async () => {
    arrowIndex.value = arrowIndex.value + 1
    let row = taskTable.value[arrowIndex.value];
    // tagsType.value = row.type;
    activeObj.value = {...row};
    TaskImages();
}

// 获取文件类型
const getFileTags = async () => {
    fileTypeLoad.value = true;
    let result = await ProjectTaskFileType({
        id: route.query.id,
        fileId: activeObj.value.id,
    })
    fileTypeLoad.value = false;
    Alltags.value = [];
    if(result.errorCode == 0){
        fileTypeList.value = result.data;
        // Alltags.value = result.data.map(item => item.name);
        for (let key in result.data) {
            for (let j = 0; j < result.data[key].length; j++) {
                const element = result.data[key][j];
                Alltags.value[element.id] = element.name;
            }
        }
    }
}
const prevStep = async () => {
    if(!activeObj.value.tagTypeId){
        return ElMessage.warning('请选择文件类型');
    }
    // await confirmTagType();
    carouselRef.value.prev();
    setTimeout(() => {
        activeIndex.value = carouselRef.value.activeIndex;
        if(documentInfo.value[activeIndex.value]?.tagTypeId){
            activeObj.value.tagTypeId = documentInfo.value[activeIndex.value].tagTypeId;
        } else{
            activeObj.value.tagTypeId = null;
        }
    }, 100);
    
}
const nextStep = async() =>{
    if(!activeObj.value.tagTypeId){
        return ElMessage.warning('请选择文件类型');
    }
    if(!documentInfo.value[activeIndex.value]?.tagTypeId){
        await confirmTagType();
    }
    if(documentInfo.value[activeIndex.value]?.tagTypeId != activeObj.value.tagTypeId){
        await confirmTagType();
    }
    carouselRef.value.next();
    setTimeout(() => {
        activeIndex.value = carouselRef.value.activeIndex;
        if(documentInfo.value[activeIndex.value].tagTypeId){
            activeObj.value.tagTypeId = documentInfo.value[activeIndex.value].tagTypeId;
        }
    }, 100);
}

const confirmTagType = async (type) => {
    // 确认标签类型
    if(!activeObj.value.tagTypeId && activeObj.value.tagTypeId != 0) {
        // 发送确认请求
        return ElMessage.warning('请选择文件类型');
    }
    let documentIndex = carouselRef.value.activeIndex;
    let tags = [{
        id: documentInfo.value[documentIndex].id,
        documentType: activeObj.value.tagTypeId
    }]
    confirmLoading.value = true;
    // 发送确认请求
    let result = await ProjectTaskFileTag({
        projectId: route.query.id,
        tags: tags
    })
    confirmLoading.value = false;

    if(result.errorCode == 0){
        // ElMessage.success('操作成功！');  
        documentInfo.value[documentIndex].tagTypeId = activeObj.value.tagTypeId;
        if(type == 1){
            console.log(arrowIndex.value , taskTable.value.length - 1, documentIndex == documentInfo.value.length - 1 && documentIndex != 0);
            
            if(arrowIndex.value == taskTable.value.length - 1){
                ElMessage.success('标记完成!');  
                return dialogVisible.value = false;
            }else if(documentIndex == documentInfo.value.length - 1 && documentIndex != 0){
                return nextCopy();
            }
            carouselRef.value.next();
        }
    }
}

// 删除
const handleDelete = async () => {
    let documentPageId = documentInfo.value[carouselRef.value.activeIndex].id
    ElMessageBox.prompt('请输入删除密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:"warning",
        inputPattern:/^.*\S+.*$/,
        inputPlaceholder: '请输入密码',
        inputErrorMessage: '请输入密码',
        inputType: 'password'
    }).then(async({ value }) => {
        dialogVisible.value = false;
        const loading = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        let res1 = await delPwConfirm(MD5(value).toString());
        if(res1.errorCode == 0){
            const res = await ProjectTaskFileDelete({id:documentPageId});
            if(res.errorCode == 0){
                ElMessage.success('删除成功');
                emit('close');
            }
        }
        loading.close();
    })
}

const dialogClose = () => {
    documentInfo.value = [];
    activeObj.value = {};
    dialogVisible.value = false;
    activeIndex.value = null;
    emit('close');
}

defineExpose({
    open
})
</script>

<style lang="scss" scoped>
.tags-container{
    min-height: 75vh;
    .left-container{
        flex: 1;
        flex-direction: column;
        .el-carousel {
            height: 100%;
            flex: 1;
            & > :deep(button.el-carousel__arrow) {
                display: none !important;
                opacity: 0;
            }
            .customized-arrow{
                display: none;
                &.arrow-disabled{
                    opacity: 0.5;
                    cursor: not-allowed;
                    .el-icon{
                        cursor: not-allowed;
                    }
                }
            }
            &:hover{
                .customized-arrow{
                    display: inline-flex;
                }
            }
            :deep(.el-carousel__container){
                height: 100%;
                .el-carousel__item{
                    &>div{
                        height: 100%;
                        width: 100%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        img{
                            width: auto;
                            height: auto;
                            display: block;
                            max-width: 100%;
                            max-height: 100%;
                            object-fit: cover; /* 图片自适应裁剪 */
                        }
                    }
                }
            }
            :deep(.el-carousel__arrow){
                background-color: rgba(31,45,61,0.5);
                font-weight: 600;
            }
        }
        .step-btn{
            width: 80%;
            margin:25px auto 10px auto;
            justify-content: space-between;
            .step-text{
                flex: 1;
                text-align: center;
                margin: 0 20px;
            }
        }

    }
    .right-container{
        flex: 1;
        padding-left: 60px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        :deep(.el-radio){
            margin-bottom: 10px;
            margin-right: 15px;
            border-width: 2px;
            .el-radio__input{
                display: none;
            }
            &:last-child{
                margin-right: 15px;
            }
        }
        .tags-Type{
         
            .论证文档{
                --el-color-primary: #409eff !important;
            }
            .招投标文件{
                --el-color-primary: #67c23a !important;
            }
            .采购文档{
                --el-color-primary: #249087 !important;
            }
            .售后维修{
                --el-color-primary: #92429D !important;
            }
          
            .论证文档, .招投标文件, .采购文档, .售后维修, .其他{
                :deep(.el-radio){
                    color: var(--el-color-primary);
                    border-color: var(--el-color-primary);
                    &.is-checked{
                        background-color: var(--el-color-primary);
                        .el-radio__label{
                            color: #fff;
                        }
                    }
                }
            }
        }
    }
}
</style>